﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Jermaine.Serialization
{
    public class StringHelper
    {
        private static readonly String ByteCodes = "0123456789ABCDEF";

        /// <summary>
        ///
        /// </summary>
        /// <param name="hex"></param>
        /// <returns></returns>
        public static byte[] HexStringToBytes(String hex) {
            hex = hex.ToUpper();
            var length = hex.Length / 2;
            var result = new byte[length];
            var charArray = hex.ToCharArray();
            for (int i = 0; i < length; i++) {
                var index = i * 2;
                result[i] = (byte)(ToByte(charArray[index]) << 4 | ToByte(charArray[index + 1]));
            }
            return result;
        }


        public static String BytesToHexString(byte[] bytes) {
            var stringBuilder = new StringBuilder();
            if (bytes == null || bytes.Length <= 0) {
                return null;
            }
            for (var i = 0; i < bytes.Length; i++) {
                var v = bytes[i] & 0xFF;
                var hv = Convert.ToString(v, 16);
                if (hv.Length < 2) {
                    stringBuilder.Append(0);
                }
                stringBuilder.Append(hv);
            }
            return stringBuilder.ToString();
        }  

        private static byte ToByte(char c) {
            var b = (byte)ByteCodes.IndexOf(c);
            return b;
        }
    }
}
